//
//  PeopleDetailViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/4/15.
//

#import "PeopleDetailViewController.h"
#import "SetInfoViewController.h"
#import "PeopleDetaileModel.h"
#import <YBPopupMenu/YBPopupMenu.h>
#import "ReportViewController.h"
#import "FunyPicDetailsViewController.h"
#import "MapDetailViewController.h"
#import "PeopleMapListViewController.h"
#import "PeopleFunyListViewController.h"
#import "IMMessageViewController.h"
#import "RealTipsPopView.h"
#import "RealViewController.h"
#import "PeopleFooterView.h"
#import "VipPopView.h"
#import "MyMiDouViewController.h"
#import "PeopleTopCollectionViewCell.h"
#import "PeopleTowCollectionViewCell.h"
#import "PeopleFunCollectionViewCell.h"
#import "AddFunyPicCollectionViewCell.h"
#import "FunUICollectionViewFlowLayout.h"
@interface PeopleDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,YBPopupMenuDelegate>
@property (nonatomic , strong) PeopleDetaileModel * meModel;
@property (nonatomic , strong) UIImageView * bgImageView;
@property (nonatomic , strong) PeopleFooterView * footView;
@property (nonatomic , assign) BOOL  isImageViewCell;
@end

@implementation PeopleDetailViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self SQ_Header];
  
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self SQ_showRealTipsView];
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SQColor(@"#4A4A4A");
    WS(weakSelf);
    if (![self.uid isEqualToString:[UserModel share].userid]) {
        [self zx_setRightBtnWithImg:SQGetImage(@"shanchu") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
           NSArray * array = @[@"举报",@"拉黑"];
            NSArray * icon = @[@"jubao",@"lahei"];
           YBPopupMenu * pop =  [YBPopupMenu showRelyOnView:btn titles:array icons:icon menuWidth:120 otherSettings:^(YBPopupMenu *popupMenu) {
                
            }];
            pop.delegate = weakSelf;
        }];
    }else{
        [self zx_setRightBtnWithText:SQNSLocalString(@"编辑") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
            SetInfoViewController * vc = [[SetInfoViewController alloc]init];
            [weakSelf SQ_pushViewControllerFull:vc];
        }];
    }
}

-(void)SQ_UIViewForSelfView{
    self.showEmpty = NO;
    
    FunUICollectionViewFlowLayout *layout = [[FunUICollectionViewFlowLayout alloc] init];
      layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView.collectionViewLayout = layout;
    [self.collectionView registerClass:[PeopleTopCollectionViewCell class] forCellWithReuseIdentifier:@"PeopleTopCollectionViewCell"];
    [self.collectionView registerClass:[PeopleTowCollectionViewCell class] forCellWithReuseIdentifier:@"PeopleTowCollectionViewCell"];
    [self.collectionView registerClass:[PeopleFunCollectionViewCell class] forCellWithReuseIdentifier:@"PeopleFunCollectionViewCell"];
    [self.collectionView registerClass:[AddFunyPicCollectionViewCell class] forCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCollectionViewHeaderView"];
    self.collectionView .dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.view addSubview:self.footView];
    [self.footView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(FootHeight+70);
    }];
    WS(weakSelf);
    [self.footView.leftBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_IMButtonClick];
    }];
    [self.footView.rightBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_RightButtonClickIM];
    }];
    
    self.footView.hidden = YES;
}


-(void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.uid forKey:@"uid"];
    [HttpTool post:Url27 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        self.meModel = [PeopleDetaileModel mj_objectWithKeyValues:httpModel.data];
        if (!self.meModel) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"该用户不存在")];
            [self SQ_popViewVC];
        }
        self.zx_navTitle = self.meModel.name;
        [PeopleDetaileModel SQ_peopleDetaile:self.jsonArray model:self.meModel];
        [self.collectionView reloadData];
        self.footView.hidden = NO;
        if ([[UserModel share].userid isEqualToString:self.uid]) {
            self.footView.hidden = YES;
        }
        //更新本地的聊天库
        IMListModel * model = [SQFMDBManager SQ_userIdGetIMListModel:self.uid];
        if ([model.peopleId isNotEmpty]) {
            model.name = self.meModel.name;
            model.portrait = self.meModel.portrait;
            [SQFMDBManager SQ_addListIM:model];
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}
-(void)SQ_IMButtonClick{
    if (!self.meModel) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"该用户不存在")];
        return;
    }
    IMListModel * model = [SQFMDBManager SQ_userIdGetIMListModel:self.uid];
    if ([model.peopleId isNotEmpty]) {
        //再跳转到im会话页面
        IMMessageViewController * vc = [[IMMessageViewController alloc]init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        if (![UserModel share].isVip) {
            [VipPopView SQ_showVipPopView];
            return;
        }
         
        NSMutableDictionary * ext = [[NSMutableDictionary alloc]init];
        [ext setObject:self.uid forKey:@"uid"];
        if ([self.meModel.name isNotEmpty]) {
            [ext setObject:self.meModel.name forKey:@"name"];
        }
        if ([self.meModel.portrait isNotEmpty])  {
            [ext setObject:self.meModel.portrait forKey:@"portrait"];
        }
        [ext setObject:@"1" forKey:@"type"];
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:@"100" forKey:@"order"];
        [dic setObject:self.uid forKey:@"content"];
        [dic setObject:[ext mj_JSONString] forKey:@"ext"];
        [[SQWebSocket shareManager]SQ_send:[dic mj_JSONString] isSend:^(BOOL isSend) {
            
        }];
    }
}

//蜜豆购买
-(void)SQ_RightButtonClickIM{
    if (!self.meModel) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"该用户不存在")];
        return;
    }
    IMListModel * model = [SQFMDBManager SQ_userIdGetIMListModel:self.uid];
    if ([model.peopleId isNotEmpty]) {
        //再跳转到im会话页面
        IMMessageViewController * vc = [[IMMessageViewController alloc]init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:self.uid forKey:@"userId"];
        [HttpTool post:Url55 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
            [self SQ_upMessage:[NSString stringWithFormat:@"%@",httpModel.data]];
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            if (httpModel.code == -4) {
                [self SQ_error];
            } else {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }
        }];
    }
}
//赠送成功
-(void)SQ_upMessage:(NSString*)roomId{
    IMListModel * listModel = [IMListModel new];
    listModel.roomId = roomId;
    listModel.name = self.meModel.name;
    listModel.portrait = self.meModel.portrait;
    listModel.peopleId = self.uid;
    listModel.content = SQNSLocalString(@"送你一颗小金豆,很想认识你");
    listModel.msgType = 10;
    listModel.time = [NSString SQ_currentTime];
    [SQFMDBManager SQ_addListIM:listModel];
    IMMessageViewController * vc = [[IMMessageViewController alloc]init];
    vc.model = listModel;
    [self.navigationController pushViewController:vc animated:YES];
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:listModel.content forKey:@"content"];
    [dic setObject:@"200" forKey:@"order"];
    [dic setObject:@"10" forKey:@"msgType"];
    [dic setObject:roomId forKey:@"roomId"];
    NSMutableDictionary * ext = [[NSMutableDictionary alloc]init];
    [ext setObject:[UserModel share].name forKey:@"name"];
    [ext setObject:[UserModel share].portrait forKey:@"portrait"];
    [ext setObject:[UserModel share].userid forKey:@"peopleId"];
    [dic setObject:[ext mj_JSONString] forKey:@"ext"];
    [[SQWebSocket shareManager]SQ_send:[dic mj_JSONString] isSend:^(BOOL isSend) {
        if (!isSend) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"链接失败,请重试")];
        }
    }];
    
}
//赠送失败
-(void)SQ_error{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"觅豆不足") message:@"当前持有觅豆不足" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"去购买") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MyMiDouViewController * vc = [[MyMiDouViewController alloc]init];
        [weakSelf SQ_pushViewControllerFull:vc];
    }];
 
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co2];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)SQ_showRealTipsView{
    if ([UserModel share].realStatus == 2|| [UserModel share].realStatus == 0) {
        return;
    }
    if ([UserModel share].gender == 1) {
        return;
    }
    RealTipsPopView * vc = [[RealTipsPopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH-60, 440)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                             parentView:nil
                                               popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleScale];
      pop.hemStyle = LSTHemStyleCenter;
      [pop pop];
    LSTPopViewWK(pop)
    WS(weakSelf);
    [vc.leftBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
        [weakSelf SQ_popViewVC];
    }];
    [vc.rightBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        RealViewController * vc = [[RealViewController alloc]init];
        [weakSelf SQ_pushViewControllerFull:vc];
        [wk_pop dismiss];
    }];
}
 
  

//拉黑 举报
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index{
    if (index ==0) {
      ReportViewController * vc = [[ReportViewController alloc]init];
      vc.userid = self.uid;
      vc.type = @"0";
      [self.navigationController pushViewController:vc animated:YES];
    } else {
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:self.uid forKey:@"pid"];
        [dic setObject:@"1" forKey:@"type"];
        [HttpTool post:Url42 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
            [self SQ_popViewVC];
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        }];
    }
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section ==1) {
        return self.jsonArray.count;
    }
    if (section ==2) {
        if (self.isImageViewCell) {
            return self.meModel.photos.count;
        } else {
            if (self.meModel.dynamicDto.count>0) {
                return 1;
            } else {
                return 0;
            }
        }
    }
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        PeopleTopCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PeopleTopCollectionViewCell" forIndexPath:indexPath];
        cell.meModel = self.meModel;
        return  cell;
    } else  if (indexPath.section ==1) {
        PeopleTowCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PeopleTowCollectionViewCell" forIndexPath:indexPath];
        cell.nameLabel.text = [self.jsonArray objectAtIndex:indexPath.item];
        return  cell;
    }
    if (self.isImageViewCell) {
        AddFunyPicCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell" forIndexPath:indexPath];
        NSDictionary * dic = [self.meModel.photos objectAtIndex:indexPath.item];
        [cell.bgImage sd_setImageWithURL:SQURLImage([dic objectForKey:@"url"])];
        cell.typeBtn.hidden = YES;
        cell.contentView.layer.cornerRadius = 2;
        return  cell;
    }
    PeopleFunCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PeopleFunCollectionViewCell" forIndexPath:indexPath];
    cell.model = [FunyModel mj_objectWithKeyValues:self.meModel.dynamicDto];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        return CGSizeMake(SCREEN_WIDETH, 342); //固定大小
    }
    if (indexPath.section ==1) {
        NSString* name = [self.jsonArray objectAtIndex:indexPath.item];
        CGSize size = [Manager SQ_boundingAttributedStringRectWithSize:CGSizeMake(SCREEN_WIDETH-68, MAXFLOAT) lineSpace:2 textFont:FONT_MEDIUM(12) string:name];
        if (size.width > SCREEN_WIDETH-70) {
            size.height =  size.height + 20;
        }
        if (size.height < 32) {
            size.height = 32;
        }
        return CGSizeMake(size.width + 28, size.height);
    }
    
    if (self.isImageViewCell) {
        return CGSizeMake((SCREEN_WIDETH-40)/3.f-1, (SCREEN_WIDETH-40)/3.f-1);
    }
    return CGSizeMake(SCREEN_WIDETH, self.meModel.dynamicHeight);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section==1) {
        return 8;
    }
    if (section==2&& self.isImageViewCell) {
        return 4;
    }
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section==1) {
        return 8;
    }
    if (section==2&& self.isImageViewCell) {
        return 4;
    }
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section ==0) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    if (section==1) {
        return UIEdgeInsetsMake(0, 24, 4, 24);
    }
    if (self.isImageViewCell) {
        return UIEdgeInsetsMake(0, 10, FootHeight+90, 10);
    }
    return UIEdgeInsetsMake(0, 0, FootHeight+90, 0);
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewHeaderView" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor clearColor];
        [headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        SQCustomButton *titleLabel = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
       
        titleLabel.text = SQNSLocalString(@"我的动态");
        [headerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView).offset(16);
            make.width.mas_equalTo(60);
            make.height.mas_equalTo(40);
            make.centerY.equalTo(headerView);
        }];
        
        SQCustomButton *titleLabel2 = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
        
        titleLabel2.text = SQNSLocalString(@"相册");
        [headerView addSubview:titleLabel2];
        [titleLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleLabel.mas_right).offset(10);
            make.width.mas_equalTo(50);
            make.height.mas_equalTo(40);
            make.centerY.equalTo(headerView);
        }];
        UIView * lineView = [[UIView alloc]init];
        lineView.backgroundColor = SQColor(@"#E133FF");
        lineView.layer.cornerRadius = 2;
        lineView.layer.masksToBounds = YES;
        [headerView addSubview:lineView];
        
        SQCustomButton * right = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
        right.text = SQNSLocalString(@"查看更多");
        right.font = FONT_REGULAR(12);
        right.layer.cornerRadius = 16;
        right.layer.masksToBounds = YES;
        right.layer.borderWidth = 1;
        right.layer.borderColor = SQColor(@"#979797").CGColor;
        right.textColor = SQColor(@"#ffffff");
        [headerView addSubview:right];
        [right mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(72);
                    make.height.mas_equalTo(32);
                    make.centerY.equalTo(titleLabel);
                    make.right.equalTo(headerView.mas_right).offset(-12);
        }];
        WS(weakSelf);
        [right setTouchBlock:^(SQCustomButton * _Nonnull button) {
            PeopleFunyListViewController *vc = [[PeopleFunyListViewController alloc]init];
            vc.uid = weakSelf.uid;
            vc.name = weakSelf.meModel.name;
            vc.portrait = weakSelf.meModel.portrait;
            [weakSelf SQ_pushViewControllerFull:vc];
        }];
        if (self.isImageViewCell) {
            titleLabel.font = FONT_MEDIUM(14);
            titleLabel.textColor = SQColor(@"#AAAAAA");
            titleLabel2.font = FONT_MEDIUM(15);
            titleLabel2.textColor = UIColor.whiteColor;
            right.hidden = YES;
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(24);
                    make.height.mas_equalTo(4);
                    make.centerX.equalTo(titleLabel2);
                    make.bottom.equalTo(titleLabel2.mas_bottom).offset(-4);
            }];
        } else {
            titleLabel.font = FONT_MEDIUM(15);
            titleLabel.textColor = UIColor.whiteColor;
            titleLabel2.font = FONT_MEDIUM(14);
            titleLabel2.textColor = SQColor(@"#AAAAAA");
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(24);
                    make.height.mas_equalTo(4);
                    make.centerX.equalTo(titleLabel);
                    make.bottom.equalTo(titleLabel.mas_bottom).offset(-4);
            }];
        }
        [titleLabel setTouchBlock:^(SQCustomButton * _Nonnull button) {
            weakSelf.isImageViewCell = NO;
            [weakSelf.collectionView reloadData];
        }];
        [titleLabel2 setTouchBlock:^(SQCustomButton * _Nonnull button) {
            weakSelf.isImageViewCell = YES;
            [weakSelf.collectionView reloadData];
        }];
        
        reusableview = headerView;
    }
    return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section ==2) {
        return CGSizeMake(SCREEN_WIDETH, 50);//宽默认
    }
    return CGSizeMake(SCREEN_WIDETH, 0);//宽默认
}
 
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==2&&self.isImageViewCell) {
        NSMutableArray * dataArray = [NSMutableArray new];
        for (int x = 0; x<self.meModel.photos.count; x++) {
            NSDictionary * dic = [self.meModel.photos objectAtIndex:x];
            YBIBImageData * data = [YBIBImageData new];
            data.imageURL = SQURLImage([dic objectForKey:@"url"]);
             data.projectiveView = [self.collectionView cellForItemAtIndexPath:indexPath];
            [dataArray addObject:data];
        }
        YBImageBrowser * brow = [YBImageBrowser new];
        brow.dataSourceArray = dataArray;
        brow.currentPage =  indexPath.item;
        [brow show];
    }
}


- (PeopleFooterView *)footView{
    if (!_footView) {
        _footView = [[PeopleFooterView alloc]initWithFrame:CGRectZero];
    }
    return _footView;
}
 
@end
